﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FileDeleteNew
{
    public partial class UserControl1 : UserControl
    {
        private string previousFolderPath = string.Empty;
        private List<FileClass> items = new List<FileClass>();//存储JSON数据数
        string fileName = "";
        string jsonPath = Application.StartupPath + "\\FileConfig.json";
        Timer delTimer, cbTimer;
        private bool stopDelTimerMsg = false; // 判断文件是否重复选择
        public string TextFileLocationValue
        {
            get { return txt_FileLocation.Text; }
            set { txt_FileLocation.Text = value; }
        }
        public int DeleteTimeValue { get; set; }
        public int TextDelTimeValue
        {
            get { return Convert.ToInt32(txt_DelTime.Text); }
            set { DeleteTimeValue = value; txt_DelTime.Text = value.ToString(); }
        }
        public bool SelectState
        {
            get
            {
                return btn_OpenFile.Enabled;
            }
            set
            {
                btn_OpenFile.Enabled = false;
            }
        }
        public int LblID { get; set; }
        public int TextLblValue
        {
            get { return Convert.ToInt32(lbl_ID.Text); }
            set { LblID = value; lbl_ID.Text = value.ToString(); }
        }
        public bool DelTimeState
        {
            get
            {
                return txt_DelTime.Enabled;
            }
            set
            {
                txt_DelTime.Enabled = false;
            }
        }
        public bool DelState
        {
            get
            {
                return cb_State.Checked;
            }
            set
            {
                cb_State.Checked = true;
            }
        }
        public UserControl1()
        {
            InitializeComponent();
            LoadData();                 //创建JSON本地文件
            InitializeFileMonitor();    //初始化定时器
            StartCBTimer();             //开启检测CheckBox状态定时器
            txt_FileLocation.Enabled = false;
            lbl_ID.Hide();
        }
        private void InitializeFileMonitor()
        {
            // 
            delTimer = new Timer(); // 设置定时器间隔为60秒（1分钟）
            delTimer.Interval = 30000;
            delTimer.Tick += new EventHandler(DelTimer_Tick);

            cbTimer = new Timer();
            cbTimer.Interval = 1000;
            cbTimer.Tick += new EventHandler(CBTimer_Tick);
        }
        private void LoadData()
        {
            if (File.Exists(jsonPath))
            {
                string json = File.ReadAllText(jsonPath);
                items = JsonConvert.DeserializeObject<List<FileClass>>(json);
            }
            else
            {
                File.Create(jsonPath);
            }
        }
        private void btn_OpenFile_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            // 检查previousFolderPath是否有值，并设置为SelectedPath
            if (!string.IsNullOrEmpty(previousFolderPath))
            {
                folderBrowserDialog.SelectedPath = previousFolderPath;
            }
            //folderBrowserDialog.SelectedPath = "D:\\vMain\\Images";
            folderBrowserDialog.Description = "选择文件夹";
            DialogResult dialogResult = folderBrowserDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                string folderPath = folderBrowserDialog.SelectedPath;
                txt_FileLocation.Text = folderPath;
                fileName = folderPath;
            }
            else
            {

            }

        }
        private void DelTimer_Tick(object sender, EventArgs e)
        {
            //// 检查是否应该显示消息
            //if (stopDelTimerMsg == false)
            //{
            //    // 显示消息或执行需要的方法
            //    MessageBox.Show("这是您的提示！");
            //    // 将标志设置为false，防止再次显示消息
            //    stopDelTimerMsg = false;
            //    // 如果不再需要Timer，可以停止或销毁它
            //    delTimer.Stop();
            //    // 如果需要再次启动Timer，可以在合适的时候调用myTimer.Start();
            //}
            if (cb_State.Checked)
            {

                int deleteDay = Convert.ToInt32(txt_DelTime.Text);
                // 使用线程安全的方式调用后台线程
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => DeleteFile(deleteDay)));
                }
                else
                {
                    DeleteFile(deleteDay);
                }
            }

        }
        public void StartDelTimer()
        {
            delTimer.Start();
        }
        private void CBTimer_Tick(object sender, EventArgs e)
        {
            if (txt_FileLocation.Text == "" || txt_DelTime.Text == "")
            {
                cb_State.Enabled = false;
            }
            else
            {
                cb_State.Enabled = true;
            }
        }
        public void StartCBTimer()
        {
            cbTimer.Start();
        }
        private void cb_State_CheckedChanged(object sender, EventArgs e)
        {
            if (cb_State.Checked)
            {
                if (lbl_ID.Text == "")
                {
                    lbl_ID.Text = WriteFileToJson();
                    if (stopDelTimerMsg)
                    {
                        StartDelTimer();

                    }
                    else
                    {
                        MessageBox.Show("该文件路径已选中，请勿重复添加改文件路径！");
                        txt_FileLocation.Text = "";
                        txt_DelTime.Text = "";
                        cb_State.Checked = false;
                    }
                }
                else
                {
                    StartDelTimer();
                }
            }
            else
            {
                StopDelTimer();
            }

        }
        public void StopDelTimer()
        {
            delTimer.Stop();
        }
        public void StopCBTimer()
        {
            cbTimer.Stop();
        }
        public string WriteFileToJson()
        {
            string jsonStr = File.ReadAllText(jsonPath);
            List<FileClass> dataObjects = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);
            // 遍历数据对象，为每个对象创建一个loactionNum实例并添加到父控件中
            FileClass fileClass = dataObjects.Find(x => x.FileLocation == txt_FileLocation.Text);   //查询JSON里的FileLocation是否存在
            string fileID = "";
            if (fileClass == null)
            {

                FileClass newItem = new FileClass();
                newItem.FileID = items.Count + 1;
                newItem.FileLocation = txt_FileLocation.Text;
                newItem.FileDelTime = Convert.ToInt32(txt_DelTime.Text);
                items.Add(newItem);
                items.Sort((x, y) => x.FileID.CompareTo(y.FileID));

                string json = JsonConvert.SerializeObject(items, Formatting.Indented);
                File.WriteAllText(jsonPath, json);
                stopDelTimerMsg = true;
                fileID = newItem.FileID.ToString();
            }
            else
            {
                stopDelTimerMsg = false;
                //MessageBox.Show("该文件路径重复选择！请选择新的文件路径!");
                //btn_OpenFile.Enabled = true;
            }
            return fileID;
        }
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("请确认是否删除当前坐标信息？", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                Control parent = this.Parent;
                if (parent != null)
                {
                    string txtLocation = txt_FileLocation.Text;
                    string jsonStr = File.ReadAllText(jsonPath);
                    List<FileClass> dataObjects = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);
                    FileClass fileClass = dataObjects.Find(x => x.FileLocation == txtLocation);
                    dataObjects.Remove(fileClass);
                    
                    // 重新排列ID
                    int newId = 1;
                    foreach (var item in dataObjects)
                    {
                        item.FileID = newId++;
                    }

                    // 序列化为新的JSON字符串
                    jsonStr = JsonConvert.SerializeObject(dataObjects, Formatting.Indented);
                    File.WriteAllText(jsonPath, jsonStr);
                    // 从父容器的控件集合中移除当前用户控件
                    parent.Controls.Remove(this);
                    // 如果需要的话，也可以在这里释放用户控件占用的资源或执行其他清理操作
                    StopDelTimer();
                    StopCBTimer();
                }
                else
                {
                    // 处理没有父容器的情况（可选）
                    MessageBox.Show("This user control has no parent container.");
                }
            }
        }
        private void RemoveAllControls(Control container)
        {
            List<string> list = new List<string>();
            string txtLocation = "";
            // 反向遍历，以避免因删除控件导致索引错位的问题
            for (int i = container.Controls.Count - 1; i >= 0; i--)
            {
                Control control = container.Controls[i];
                if (control is UserControl1 userControl)
                {
                    // 检查用户控件内是否有CheckBox，并且是否被选中
                    CheckBox checkedCheckBox = userControl.Controls.OfType<CheckBox>()
                       .FirstOrDefault(cb => cb.Checked);
                    // 如果找到被选中的CheckBox，则删除整个用户控件
                    if (checkedCheckBox != null)
                    {
                        var textBoxes = control.Controls.OfType<TextBox>();
                        foreach (var textBox in textBoxes)
                        {
                            txtLocation = textBox.Text;
                        }
                        string jsonStr = File.ReadAllText(jsonPath);

                        List<FileClass> dataObjects = JsonConvert.DeserializeObject<List<FileClass>>(jsonStr);

                        FileClass fileClass = dataObjects.Find(x => x.FileLocation == txtLocation);
                        if (fileClass != null)
                        {
                            dataObjects.Remove(fileClass);
                            jsonStr = JsonConvert.SerializeObject(dataObjects, Formatting.Indented);
                            File.WriteAllText(jsonPath, jsonStr);
                            container.Controls.Remove(userControl);
                            // 可能还需要处理用户控件的释放或事件解绑
                            userControl.Dispose(); // 如果确定不再需要这个控件的实例，可以调用Dispose
                        }
                        else
                        {
                            container.Controls.Remove(userControl);
                            // 可能还需要处理用户控件的释放或事件解绑
                            userControl.Dispose(); // 如果确定不再需要这个控件的实例，可以调用Dispose
                        }

                    }
                }
                // 如果控件本身是一个容器，递归检查它内部的控件
                else if (control.HasChildren)
                {
                    RemoveAllControls(control);
                }
            }
        }
        private void DeleteFile(int saveDay)
        {
            try
            {
                //string fileOriginAll = txt_FileLocation.Text + "\\Origin\\ALL\\";
                string fileOrigin = txt_FileLocation.Text + "\\Origin\\";

                //string fileRenderAll = txt_FileLocation.Text + "\\Render\\ALL\\";
                string fileRender = txt_FileLocation.Text + "\\Render\\";

                DateTime nowTime = DateTime.Now;
                string[] filesorigin = Directory.GetDirectories(fileOrigin, "*.*", SearchOption.AllDirectories);  //获取该目录下所有文件    
                string[] filesrender = Directory.GetDirectories(fileRender, "*.*", SearchOption.AllDirectories);  //获取该目录下所有文件    
                foreach (string file in filesorigin)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    string[] fileSplit = file.Split('\\');
                    string fileTime = fileSplit[fileSplit.Length - 1];
                    if (fileTime == "ALL")
                    {
                        continue;
                    }
                    DateTime dateTime = DateTime.Parse(fileTime.Trim());
                    TimeSpan tDay = nowTime - dateTime;
                    int tDayTime = tDay.Days;
                    //TimeSpan t = nowTime - fileInfo.CreationTime;  //当前时间  减去 文件创建时间               
                    //int day = t.Days;
                    if (tDayTime > saveDay)   //保存的时间 ；  单位：天                
                    {
                        Directory.Delete(file, true);  //删除超过时间的文件夹               
                    }
                }
                foreach (string file in filesrender)
                {
                    FileInfo fileInfo = new FileInfo(file);
                    string[] fileSplit = file.Split('\\');
                    string fileTime = fileSplit[fileSplit.Length - 1];
                    if (fileTime == "ALL")
                    {
                        continue;
                    }
                    DateTime dateTime = DateTime.Parse(fileTime.Trim());
                    TimeSpan tDay = nowTime - dateTime;
                    int tDayTime = tDay.Days;
                    //TimeSpan t = nowTime - fileInfo.CreationTime;  //当前时间  减去 文件创建时间               
                    //int day = t.Days;
                    if (tDayTime > saveDay)   //保存的时间 ；  单位：天                
                    {
                        Directory.Delete(file, true);  //删除超过时间的文件夹               
                    }
                }

            }
            catch (Exception e)
            {
                MessageBox.Show("请选择流程文件路径，请勿选择其他非流程文件！\\" + e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally { }
        }
    }
}
